<?php
class Search_Model_Search extends Promotor_Model_Abstract {

	protected $_cachedMethods = array(
		'find'
	);

	public function find($find) {
		$result = array();

		if (is_string($find) && strlen($find) > 1) {
			// prepare find
			$this->prepareFind($find);
			$find = sprintf('%%%s%%', (string) $find);

			$db = Zend_Db_Table_Abstract::getDefaultAdapter();
	
			$select1 = new Zend_Db_Select($db);
			$select1->from('site', array('id', 'name','content', 'time_create', 'type' => new Zend_Db_Expr('"site"')));
			
			$select2 = new Zend_Db_Select($db);
			$select2->from('news', array('id', 'name','content', 'time_create', 'type' => new Zend_Db_Expr('"news"')));
	
			$select1->where('name LIKE ?', $find)
					->orWhere('content LIKE ?', $find);
			$select2->where('name LIKE ?', $find)
					->orWhere('content LIKE ?', $find);
	
			$select = new Zend_Db_Select($db);
			$select->union(array($select1, $select2));
	
			try {
				$stmt = $select->query();
				$result = $stmt->fetchAll();
				$this->_setStatus(self::SUCCESS);
			} catch(Zend_Db_Exception $e){
				$this->_addException($e);
				$this->_setStatus(self::FAILURE);
			}
		}

		return $result;
	}
	
	/**
	 * @param string $find
	 * @return string
	 */
	public function prepareFind($find) {
		$filter = new Zend_Filter();
		$filter->addFilter(new KontorX_Filter_SearchText());
		$filter->addFilter(new KontorX_Filter_MagicQuotes());

		return $filter->filter((string) $find);
	}
}